package com.qdu.web.controller.bussiness;

import java.security.Security;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.qdu.common.core.domain.entity.SysUser;
import com.qdu.common.core.domain.model.LoginUser;
import com.qdu.common.utils.SecurityUtils;
import com.qdu.common.utils.StringUtils;
import com.qdu.framework.web.service.TokenService;
import com.qdu.system.mapper.SysUserMapper;
import com.qdu.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qdu.common.annotation.Log;
import com.qdu.common.core.controller.BaseController;
import com.qdu.common.core.domain.AjaxResult;
import com.qdu.common.enums.BusinessType;
import com.qdu.bussiness.domain.BusRecharge;
import com.qdu.bussiness.service.IBusRechargeService;
import com.qdu.common.utils.poi.ExcelUtil;
import com.qdu.common.core.page.TableDataInfo;

/**
 * 充值记录Controller
 *
 * @author qdu
 * @date 2022-03-13
 */
@RestController
@RequestMapping("/bussiness/recharge")
public class BusRechargeController extends BaseController
{
    @Autowired
    private IBusRechargeService busRechargeService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('bussiness:recharge:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusRecharge busRecharge)
    {
        startPage();
        List<BusRecharge> list = busRechargeService.selectBusRechargeList(busRecharge);
        return getDataTable(list);
    }

    /**
     * 导出充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('bussiness:recharge:export')")
    @Log(title = "充值记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusRecharge busRecharge)
    {
        List<BusRecharge> list = busRechargeService.selectBusRechargeList(busRecharge);
        ExcelUtil<BusRecharge> util = new ExcelUtil<BusRecharge>(BusRecharge.class);
        util.exportExcel(response, list, "充值记录数据");
    }

    /**
     * 获取充值记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('bussiness:recharge:query')")
    @GetMapping(value = "/{rechargeId}")
    public AjaxResult getInfo(@PathVariable("rechargeId") Long rechargeId)
    {
        return AjaxResult.success(busRechargeService.selectBusRechargeByRechargeId(rechargeId));
    }

    /**
     * 新增充值记录
     */
    @PreAuthorize("@ss.hasPermi('bussiness:recharge:add')")
    @Log(title = "充值记录", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody BusRecharge busRecharge)
    {
        // 修改账户余额
        // 这里应该是通过查询前端传递过来的userName, 而不是获取当前人的账号
        // 应该是当时测试的时候，写死 忘记改了
        SysUser sysUser = userMapper.selectUserByUserName(busRecharge.getRechargeUser());
        if(sysUser == null){
            return AjaxResult.error("用户不存在！");
        }
        String balance = sysUser.getBalance();
        Double bal = 0.00;
        Double amount = 0.00;
        if(StringUtils.isNotEmpty(balance)){
            bal = Double.parseDouble(balance);
        }
        String rechargeAmount = busRecharge.getRechargeAmount();
        if(StringUtils.isNotEmpty(rechargeAmount)){
            amount = Double.parseDouble(rechargeAmount);
        }else {
            return AjaxResult.error("请填写充值金额！");
        }
        SysUser updateUser = new SysUser();
        updateUser.setUserId(sysUser.getUserId());
        updateUser.setBalance(String.valueOf(bal + amount));
        int udpUserRes = userMapper.updateUser(updateUser);
        if(udpUserRes < 1){
            return AjaxResult.error("充值失败");
        }
        busRechargeService.insertBusRecharge(busRecharge);
        // 只更新当前用户的缓存余额
        LoginUser loginUser = getLoginUser();
        if(loginUser.getUsername().equals(busRecharge.getRechargeUser())){
            loginUser.getUser().setBalance(String.valueOf(bal + amount));
            tokenService.setLoginUser(loginUser);
        }
        return AjaxResult.success();
    }

    /**
     * 修改充值记录
     */
    @PreAuthorize("@ss.hasPermi('bussiness:recharge:edit')")
    @Log(title = "充值记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusRecharge busRecharge)
    {
        return toAjax(busRechargeService.updateBusRecharge(busRecharge));
    }

    /**
     * 删除充值记录
     */
    @PreAuthorize("@ss.hasPermi('bussiness:recharge:remove')")
    @Log(title = "充值记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{rechargeIds}")
    public AjaxResult remove(@PathVariable Long[] rechargeIds)
    {
        return toAjax(busRechargeService.deleteBusRechargeByRechargeIds(rechargeIds));
    }
}
